package com.tjl.warehouse.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;


public class JWTUtils {

    // 应使用更安全的方式存储这个密钥，
    private static final String SECRET_KEY = "Hello!World!T?**$%^3462";

    @Value("${warehouse.expire-time}")
    static Long expirationTimeMs = 1000 * 60 * 60 * 24 * 2L;

    public static String generateToken(int userId) {
        Date expiresAt = new Date(System.currentTimeMillis() + expirationTimeMs);
        return JWT.create()
                .withClaim("userId", userId)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }



    // 生成Token
    public static String generateToken(int userId, int userRole) {
        Date expiresAt = new Date(System.currentTimeMillis() + expirationTimeMs);
        return JWT.create()
                .withClaim("userId", userId)
                .withClaim("userRole", userRole)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    // 解析并验证Token
    public static DecodedJWT verifyToken(String token) throws JWTVerificationException {
        try {
            return JWT.require(Algorithm.HMAC256(SECRET_KEY))
                    .build()
                    .verify(token);
        } catch (JWTVerificationException e) {
            throw new JWTVerificationException("Token验证失败: " + e.getMessage());
        }
    }

    // 获取Token中的UserId
    public static int getUserIdFromToken(String token) throws JWTVerificationException {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getClaim("userId").asInt();
    }

    // 获取Token中的UserRole 暂时不用
    @Deprecated
    public static String getUserRoleFromToken(String token) throws JWTVerificationException {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getClaim("userRole").asString();
    }

    // 检查Token是否有效
    public static boolean isTokenExpired(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getExpiresAt().before(new Date());
        } catch (Exception e) {
            return true; // 如果解码失败，也认为是过期或无效的Token
        }
    }
}